
var SupportHome = {
    
    init: function() {
        this.setupTable();
    },
    
    setupTable: function() {
        var self = this;
        
        $("#org_table tbody tr a").click(function(e) {
            e.preventDefault();
            
            $("#org_table tbody tr").removeClass("selected");
            $(this).parents("tr").addClass("selected");
            
            var url = $(this).attr('href');
            
            $.get(url, function(data) {
                self.displayOrgData(data);
            });
        });
        
        $("#org_table tbody tr:first a").click();
        
        $("#org_table tbody tr .disable-btn").click(function(e) {
            e.stopPropagation();
            
            self.activateOrganisation( $(this).data('id'), !$(this).data('active') );
        });
    },
    
    displayOrgData: function(data) {
        $("#org_details_body").html(data);
        
        $("#org_details_body #export_btn").click(function() {
            alert("Exporting Organisation Data");
        });
    },
    
    activateOrganisation: function(organisation_id, activate) {
        var self = this;
        
        if( !confirm("Are you sure you want to disable this organisation?") ) {
            return;
        }
        
        var url = $("#organisation_activate_url").val();
        var params = {
            organisation_id: organisation_id,
            activate: activate
        };

        $.ajax({
            url: url,
            data: params,
            type: 'post',
            dataType: 'json',
            success: function(response) {
                $(".disable-btn").each(function() {
                    if( $(this).data("id") == organisation_id ) {
                        if( response.active == "1" ) {
                            $(this).removeClass("btn-warning").addClass("btn-success");
                        }
                        
                        else {
                            $(this).removeClass("btn-success").addClass("btn-warning");
                        }
                        
                        $(this).data('active', response.active);
                    }
                });
            },
            error: function(xhr) {
                console.log(xhr.responseText);
            }
        });
        
        
    }
};

$(document).ready(function() {
    SupportHome.init();
});
